package com.boot.domain;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * xml 转换和解析工具类
 */
public class XMLUtils2 {


    private static Map<String, XStream> XSTREAM_OBJ = new ConcurrentHashMap<>();



    public static <T> T fromXml(String xml, Class<T> t) {
        try {
            XStream xstream = getXStreamObjInstance(t);
            return (T) xstream.fromXML(xml);
        }catch (Exception e){
        }
        return null;
    }

    public static String toXml(Object obj){
        return getXStreamObjInstance(obj.getClass()).toXML(obj);
    }

    public static String toXmlOneLine(Object obj){

        Writer writer = new StringWriter();
        //设置压缩输出，NoNameCoder 不对下划线转义处理
        CompactWriter compactWriter = new CompactWriter(writer,new NoNameCoder());
        XStream xStream =   getXStreamObjInstance(obj.getClass());
        xStream.marshal(obj, compactWriter);
        return writer.toString();
    }

    private static XStream getXStreamObjInstance(Class t) {
        XStream xStream = XSTREAM_OBJ.get(t.getName());
        if (xStream == null) {
            synchronized (XMLUtils2.class) {
                xStream = XSTREAM_OBJ.get(t.getName());
                if(xStream == null) {
                    xStream = getXStreamInstance();
                    xStream.processAnnotations(t);
                    xStream.aliasSystemAttribute(null,"class");
                    XSTREAM_OBJ.put(t.getName(), xStream);
                }
                return xStream;
            }
        }
        return xStream;
    }

    private static XStream getXStreamInstance() {


        XStream xStream = new XStream(new Xpp3Driver(new NoNameCoder()));
        xStream.ignoreUnknownElements();
        return xStream;
    }


}
